package com.mo.demo.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GuavaRemoveListenerTest {


    public static void main(String[] args) throws InterruptedException {

        RemovalListener<String, Object> listener = new RemovalListener<String, Object>() {
            public void onRemoval(RemovalNotification<String, Object> notification) {
                log.info("缓存[key={}]被移除",notification.getKey());
            }
        };

        Cache<String, Object> cache = CacheBuilder.newBuilder()
                .removalListener(listener)
                .build();

        Object value = new Object();

        cache.put("1",value);

        Thread.sleep(2000);

        cache.invalidate("1");

        // 输出：
        // 13:34:06.990 [main] INFO com.mo.demo.guava.GuavaRemoveListenerTest - 缓存[key=1]被移除

    }
}
